package keeper.servlet;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keeper.event.Event;
import keeper.event.EventListener;
import keeper.util.NameRegister;
import keeper.util.RegistException;
import keeper.util.ScriptWriter;

/**
 * 
 * @author hliang@126.com
 *
 */
public class Keeper extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Keeper() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
		String script = config.getInitParameter("ScriptName");
		String path = config.getServletContext().getRealPath("");
		if(script == null) {
			script = "keeper.js";
		}
		String filePath = path+script;
		File f = new File(filePath);
		if(!f.exists()) {
			ScriptWriter w = new ScriptWriter();
			w.output(f);	
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String eventName = request.getParameter("event");
		NameRegister reg = NameRegister.getInstance();
		Event event = null;
		try {
			event = reg.getEvent(eventName);
			if(event == null) {
				event = new Event(eventName,this);
				reg.registeEvent(eventName, event);
			}
			if(event.getServlet() == null) {
				event.setServlet(this);
			}
			
		} catch (RegistException e1) {
			e1.printStackTrace();
		}
		synchronized(this) {
			while(!event.isProcess()) {
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		EventListener listener = event.getListener();
		if(listener != null) {
		   listener.process(request,response);
		}	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(request, response);
	}
}
